//
//  imagepage.m
//  hw3
//
//  Created by fcbayern on 2020/12/6.
//  Copyright © 2020 fcbayern. All rights reserved.
//

#import "imagepage.h"
#import "mycell.h"
#import "Masonry.h"
#import "AFNetworking.h"

@interface imagepage ()
@property(strong,nonatomic)UILabel * Title;
@property (nonatomic, strong) UITableView *tableView;

@property(nonatomic,strong)UIButton * load;
@property(nonatomic,strong)UIButton * deleteall;
@property(nonatomic,strong)UIButton * deletecache;
@property(nonatomic,strong)NSMutableArray * imagearray;
@end

@implementation imagepage

- (void)viewDidLoad {
    [super viewDidLoad];
    _imagearray = [[NSMutableArray alloc]init];
    
    self.title = @"显示图片";
    self.view.backgroundColor = [UIColor whiteColor];
    _Title = [[UILabel alloc]init];
    [self.view addSubview:_Title];
    _Title.text = @"显示图片";
    _Title.font = [UIFont systemFontOfSize:20];
    _Title.textAlignment = UITextAlignmentCenter;
    [_Title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(self.view.frame.size.height*0.1);
        make.centerX.equalTo(self.view);
        make.height.equalTo(self.view.mas_width).multipliedBy(0.2);
        make.width.equalTo(self.view.mas_width).multipliedBy(0.6);
    }];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor =[UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view).multipliedBy(0.9);
        make.top.equalTo(_Title.mas_bottom);
        make.bottom.equalTo(self.view.mas_bottom).with.offset(-self.view.frame.size.height*0.3);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    
    _load = [[UIButton alloc]init];
    _deleteall = [[UIButton alloc]init];
    _deletecache = [[UIButton alloc]init];
    _load.layer.borderWidth = 1;
    _deletecache.layer.borderWidth = 1;
    _deleteall.layer.borderWidth = 1;
    [_load setTitle:@"加载图片" forState:UIControlStateNormal];
    _load.font = [UIFont systemFontOfSize:20];
    [_load setTitleColor:[UIColor colorWithRed: 0/ 255.0 green:191 / 255.0 blue:255 / 255.0 alpha:1] forState:UIControlStateNormal];
    [_deletecache setTitle:@"删除缓存" forState:UIControlStateNormal];
    _deletecache.font = [UIFont systemFontOfSize:20];
    [_deletecache setTitleColor:[UIColor colorWithRed: 0/ 255.0 green:191 / 255.0 blue:255 / 255.0 alpha:1] forState:UIControlStateNormal];
    [_deleteall setTitle:@"清空图片" forState:UIControlStateNormal];
    _deleteall.font = [UIFont systemFontOfSize:20];
    [_deleteall setTitleColor:[UIColor colorWithRed: 0/ 255.0 green:191 / 255.0 blue:255 / 255.0 alpha:1] forState:UIControlStateNormal];
    
    
    [self.view addSubview:_load];
    [self.view addSubview:_deletecache];
    [self.view addSubview:_deleteall];
    
    [_load mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view).multipliedBy(0.6);
        make.top.equalTo(_tableView.mas_bottom).with.offset(15);
        make.height.equalTo(self.view.mas_width).multipliedBy(0.15);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    [_deleteall mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view).multipliedBy(0.6);
        make.top.equalTo(_load.mas_bottom).with.offset(15);
        make.height.equalTo(self.view.mas_width).multipliedBy(0.15);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    [_deletecache mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view).multipliedBy(0.6);
        make.top.equalTo(_deleteall.mas_bottom).with.offset(15);
        make.height.equalTo(self.view.mas_width).multipliedBy(0.15);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    [_load addTarget:self action:@selector(loadpic:) forControlEvents:UIControlEventTouchUpInside];
    [_deleteall addTarget:self action:@selector(deletelist:) forControlEvents:UIControlEventTouchUpInside];
    [_deletecache addTarget:self action:@selector(btndeletecache:) forControlEvents:UIControlEventTouchUpInside];
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    return 150;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return [UIView new];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _imagearray.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    mycell * cell = [tableView dequeueReusableCellWithIdentifier:@"cellid"];
    if (cell == nil) {
        cell = [[mycell alloc] init];
            
    }
    NSString * temp = [[NSString alloc]initWithFormat:@"%@%d%@",@"第",indexPath.section+1,@"张图"];
    cell.number.text = temp;
    
    NSString * tempstr =[NSHomeDirectory() stringByAppendingPathComponent:_imagearray[indexPath.section]];
    
    UIImage * header = [UIImage imageWithContentsOfFile:tempstr];
        cell.picture.image = header;
    return cell;
}


-(void)btndeletecache:(id)sender{
    [_imagearray removeAllObjects];
    [self delcache];
    [_tableView reloadData];
}

-(void)loadpic:(id)sender{
    if(_imagearray.count == 5){
        [_tableView reloadData];
        return;
    }
    
    int check = 0;
    NSString * temppath2 = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    NSFileManager * fm = [NSFileManager defaultManager];
    NSArray * temparr = [fm contentsOfDirectoryAtPath:temppath2 error:nil];
    
    temparr = [temparr sortedArrayUsingSelector:@selector(compare:)];
    
    for(id key in temparr){
        NSString * tempstr = key;
        if([tempstr rangeOfString:@".jpg"].location != NSNotFound){
            ++check;
        }
    }
    if(check == 0){
        NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:[UIImage imageNamed:@"load1.png"],[UIImage imageNamed:@"load2.png"],[UIImage imageNamed:@"load3.png"],[UIImage imageNamed:@"load4.png"], nil];
        
        UIImageView *imageView = [[UIImageView alloc] init];
        [self.view addSubview:imageView];
        
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.centerY.equalTo(self.view);
            make.width.equalTo(self.view.mas_width).multipliedBy(0.5);
            make.height.equalTo(self.view.mas_width).multipliedBy(0.5);
        }];
         imageView.animationImages = array; //动画图片数组
         imageView.animationDuration = 0.2; //执行一次完整动画所需的时长
         imageView.animationRepeatCount = 1;  //动画重复次数 0表示无限次，默认为0
         [imageView startAnimating];

        NSString * pic1 = @"https://hbimg.huabanimg.com/d8784bbeac692c01b36c0d4ff0e072027bb3209b106138-hwjOwX_fw658";
        NSString * pic2 = @"https://hbimg.huabanimg.com/6215ba6f9b4d53d567795be94a90289c0151ce73400a7-V2tZw8_fw658";
        NSString * pic3 = @"https://hbimg.huabanimg.com/834ccefee93d52a3a2694535d6aadc4bfba110cb55657-mDbhv8_fw658";
        NSString * pic4 =  @"https://hbimg.huabanimg.com/f3085171af2a2993a446fe9c2339f6b2b89bc45f4e79d-LacPMl_fw658";
        NSString * pic5 = @"https://hbimg.huabanimg.com/e5c11e316e90656dd3164cb97de6f1840bdcc2671bdc4-vwCOou_fw658";
        NSMutableArray * temparrpic = [[NSMutableArray alloc] init];
        [temparrpic addObject:pic1];
        [temparrpic addObject:pic2];
        [temparrpic addObject:pic3];
        [temparrpic addObject:pic4];
        [temparrpic addObject:pic5];
        
        for(int i = 0;i<5;++i){
            UIImage * im = [UIImage imageWithData:[NSData  dataWithContentsOfURL:[NSURL URLWithString:temparrpic[i]]]];
            NSString * savepath = [self saveImageToCacheUseImage:im];
            [_imagearray addObject: savepath];
        }
    }
    else{
        for(id key in temparr){
            NSString * tempstr = key;
            if([tempstr rangeOfString:@".jpg"].location != NSNotFound){
                NSString * temppath3 = [@"Library/Caches" stringByAppendingPathComponent:tempstr];
    
                [_imagearray addObject: temppath3];
            }
        }
    }

    [_tableView reloadData];
    
    
}

-(void)deletelist:(id)sender{
    [_imagearray removeAllObjects];
    [_tableView reloadData];
}


-(NSString *)saveImageToCacheUseImage:(UIImage *)image
{
    //获取当前时间戳拼接到文件尾部,防止存储图片多时地址重复
    NSDate *currentDate = [NSDate dateWithTimeIntervalSinceNow:0];
    // *1000 是精确到毫秒，不乘就是精确到秒
    NSTimeInterval currentTime=[currentDate timeIntervalSince1970]*1000;
    NSString *timeString = [NSString stringWithFormat:@"%.0f", currentTime];
    
    //这个路径是存储到本地用的图片后缀地址
    NSString *savePath= [NSString stringWithFormat:@"Library/Caches/image_%@.jpg", timeString];
    NSLog(@"%@",savePath);
    //这个路径是将图片存入沙盒时的路径
    NSString *imageAllPath = [NSHomeDirectory() stringByAppendingPathComponent:savePath];
    //存储图片到沙盒,并返回结果
    BOOL result =[UIImagePNGRepresentation(image) writeToFile:imageAllPath atomically:YES];
    return savePath;
}

-(void)delcache{
    NSFileManager *manager = [NSFileManager defaultManager];

    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

    NSEnumerator *filesEnumerator = [[manager subpathsAtPath:path] objectEnumerator];//枚举 caches下所有文件路径

    NSString *filePath;//文件名

    while ((filePath = [filesEnumerator nextObject]) != nil) {

        NSString *string = [path stringByAppendingPathComponent:filePath];

        [manager removeItemAtPath:string error:nil];

    }
}



@end
